package com.atguigu.yygh.user.service.impl;
import com.atguigu.yygh.common.exception.HospitalException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.acl.UserQueryVo;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.*;


@Service
public class UserInfoServiceImpl extends
        ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //如果有openid就是微信登录,先查找
        //如果数据库存在手机号码,不操作
        //直接手机号登录
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",loginVo.getPhone());

        //微信登录后绑定手机号
        if(StringUtils.isNotEmpty(loginVo.getOpenid())){
            UserInfo byOpenid = this.getByOpenid(loginVo.getOpenid());
            byOpenid.setPhone(loginVo.getPhone());
            //发送短信验证手机号,才能更新对应的手机号
            if(this.compareCodeFromRedis(phone,loginVo.getCode())){
                QueryWrapper<UserInfo> wrapper1 = new QueryWrapper<>();
                wrapper.eq("openid",loginVo.getOpenid());
                baseMapper.update(byOpenid,wrapper1);
                HashMap<String, Object> map = new HashMap<>();
                String token = JwtHelper.createToken(byOpenid.getId(), byOpenid.getPhone());
                map.put("token",token);
                map.put("name",byOpenid.getPhone());

            }

        }


        UserInfo userInfo = baseMapper.selectOne(wrapper);
        //没有号码就创建用户插入数据库
        if(userInfo==null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setName("");
            userInfo.setStatus(1);
            long random = new Random().nextLong();
            userInfo.setId(random);
            this.save(userInfo);
        }
        if(userInfo.getStatus() == 0) {
            throw new HospitalException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //如果查找这个用户,没有设置名字就设置他的名字
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }


        //返回结果
        HashMap<String, Object> map = new HashMap<>();

        if(this.compareCodeFromRedis(phone,loginVo.getCode())){
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token",token);
            map.put("name",name);
            return map;

        }


        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token","");
        map.put("name","");



        return map;
    }

    @Override
    public UserInfo getByOpenid(String openId) {
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("openId",openId);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Map<String, Object> loginByOpenId(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String openid = loginVo.getOpenid();
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(openid)){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //如果有openid就是微信登录,先查找
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",loginVo.getOpenid());
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        //如果没有查到openid,则,直接创建手机用户
        if(userInfo==null){
            //返回结果
            HashMap<String, Object> map = new HashMap<>();

            if(this.compareCodeFromRedis(phone,loginVo.getCode())){
                UserInfo userInfo1 = new UserInfo();
                userInfo.setPhone(loginVo.getPhone());
                userInfo.setStatus(1);
                userInfo.setNickName(loginVo.getPhone());
                baseMapper.insert(userInfo);
                String token = JwtHelper.createToken(userInfo.getId(), loginVo.getPhone());
                map.put("token",token);
                map.put("name", loginVo.getPhone());
                return map;

            }
        }
        //微信登录后绑定手机号

            userInfo.setPhone(loginVo.getPhone());

            //发送短信验证手机号,才能更新对应的手机号
            if(this.compareCodeFromRedis(phone,loginVo.getCode())){
                QueryWrapper<UserInfo> wrapper1 = new QueryWrapper<>();
                wrapper.eq("openid",loginVo.getOpenid());
                baseMapper.update(userInfo,wrapper1);
                HashMap<String, Object> map = new HashMap<>();
                String token = JwtHelper.createToken(userInfo.getId(), userInfo.getPhone());
                map.put("token",token);
                map.put("name",userInfo.getName());
                return map;
            }

        




            return null;
    }
    //更新用户认证信息
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        if(StringUtils.isNotEmpty(userAuthVo.getCertificatesType())&&
           StringUtils.isNotEmpty(userAuthVo.getCertificatesNo())
        ){
            userInfo.setCertificatesType(userAuthVo.getCertificatesType());
            userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
            userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
            userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
            baseMapper.updateById(userInfo);
        }

    }



    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //orderQueryVo获取条件值
        String keyword = userInfoQueryVo.getKeyword(); //医院名称
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//就诊人名称
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(keyword)) {
            wrapper.like("phone ",keyword);
            wrapper.or().like("name",keyword);
        }
//        if(patientId!=null) {
//            wrapper.eq("patient_id",patientId);
//        }
//        if(!StringUtils.isEmpty(orderStatus)) {
//            wrapper.eq("order_status",orderStatus);
//        }
//        if(!StringUtils.isEmpty(createTimeBegin)) {
//            wrapper.ge("reserve_date",createTimeBegin);
//        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("update_time",createTimeEnd);
        }
//        //调用mapper的方法
        IPage<UserInfo> pages = userInfoMapper.selectPage(pageParam, wrapper);
//        //编号变成对应值封装
//        pages.getRecords().stream().forEach(item -> {
//            this.packOrderInfo(item);
//        });
//        NO_AUTH(0, "未认证"),
//                AUTH_RUN(1, "认证中"),
//                AUTH_SUCCESS(2, "认证成功"),
//                AUTH_FAIL(-1, "认证失败"),
//        ;
        List<UserInfo> records = pages.getRecords();
        for (UserInfo record : records) {
            String authStatusString = AuthStatusEnum.getStatusNameByStatus(record.getAuthStatus());
            Integer status = record.getStatus();

            Map<String, Object> param = record.getParam();
            param.put("authStatusString",authStatusString);
            if(status==0){
                param.put("statusString","锁定");
            }else if(status == 1){
                param.put("statusString","正常");
            }else{
                param.put("statusString","状态异常");
            }
            
        }
        return pages;
    }

    @Override
    public void lock(Integer id, Integer state) {
        if(state!=0 && state!=1){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        UserInfo userInfo = userInfoMapper.selectById(id);
        userInfo.setStatus(state);
        userInfoMapper.updateById(userInfo);

    }

    @Override
    public UserInfo show(Integer id) {
        return userInfoMapper.selectById(id);
    }

    @Override
    public void approval(Integer id, Integer state) {

        String statusNameByStatus = AuthStatusEnum.getStatusNameByStatus(state);
        if("".equals(statusNameByStatus) && statusNameByStatus==null){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        UserInfo userInfo = userInfoMapper.selectById(id);
        userInfo.setAuthStatus(state);
        userInfoMapper.updateById(userInfo);
    }

    public boolean compareCodeFromRedis(String phone,String code){

        //通过redis得到阿里云的验证码,对比用户验证码
        String codeFromRedis= redisTemplate.opsForValue().get(phone);
        if(codeFromRedis!=null && codeFromRedis.equals(code) ){
            return true;
        }
        return false;
    }



}